home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 6184 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.6 KB  |  75 lines

  1. Path: news.th-darmstadt.de!news!enno
  2. From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Memory allocation.
  5. Date: 10 Feb 1996 20:48:54 GMT
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Distribution: world
  8. Message-ID: <ENNO.96Feb10214855@kitz.inferenzsysteme.informatik.th-darmstadt.de>
  9. References: <1996Feb10.161530.26449@wisipc.weizmann.ac.il>
  10. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  11. In-reply-to: Kajdan Dimitry's message of Sat, 10 Feb 1996 16:15:30 GMT
  12.  
  13. In article <1996Feb10.161530.26449@wisipc.weizmann.ac.il> Kajdan Dimitry <cerlpvk> writes:
  14.  
  15.    I'm a starter so the question may seem stupid.
  16.  
  17.    Would someone explain why this program works?
  18.  
  19.    int* func()
  20.    {
  21.  
  22.  
  23.     int b[10];
  24.       for(int i=0;i<9;i++)
  25.     b[i]=i;
  26.      return b;  
  27.    }
  28.  
  29.    int main(){
  30.  
  31.     int* x= func();
  32.  
  33.  
  34.      cout<<x[2]<<endl;
  35.      return(1);
  36.    }
  37.  
  38.    The point is that b is allocated on the stack i.e without "new".
  39.  
  40.    Thanks in advance.
  41.  
  42. This program _may_ works. In your example the elements of the array
  43. are obviously still accessible, although they are not part of the
  44. actual stack-frame of the main procedure. It's very likely that the
  45. slightly modified program
  46.  
  47. >>>>
  48. #include <iostream.h>
  49.  
  50. int* func(int off)
  51. {
  52.  int b[10];
  53.    for(int i=0;i<9;i++)
  54.      b[i]=i+off;
  55.   return b;  
  56. }
  57.  
  58. int main()
  59. {
  60.  int* x= func(0);
  61.  func(1);
  62.  
  63.  cout<<x[2]<<endl;
  64.  return(1);
  65. }
  66. <<<<
  67.  
  68. produces a different result, because the same memory gets modified in the
  69. 2nd call of 'func'. However the correct explaination completely depends on
  70. your environment. And of course - in general you cannot rely on this behavior.
  71.  
  72.     Enno
  73. --
  74.     Enno
  75.